﻿using UnityEngine;
using System.Collections;

public class GameController : MonoBehaviour {
	public static GameController gc;
	public static PlayerController player;
	public AStar astar;
	public GridCell[,] board;
	public int boardWidth;
	public int boardHeight;

	public int[,] navBoard;

	public bool showPath;
	public bool showStatInfo;

	public LineRenderer lineRenderer;

	public GameObject gridCellPrefab;
	// Use this for initialization
	void Awake () {
		gc = this;
		Debug.Log(boardWidth + ", " + boardHeight);
		navBoard = new int[boardHeight,boardWidth];
		player = GameObject.Find("invisible leader").GetComponent<PlayerController>();
		initializeBoard();
		lineRenderer = GetComponent<LineRenderer> ();
	}

	void initializeBoard(){
		if(boardWidth == 0)
			boardWidth = 17;
		if(boardHeight == 0)
			boardHeight = 10;
		for (int i = 0; i < boardWidth; i++) {
			for(int j = 0; j < boardHeight; j++){
				Instantiate(gridCellPrefab, new Vector3(0,0,0), Quaternion.identity);
			}
		}
		int index = 0;
		int jindex = 0;
		board = new GridCell[boardWidth, boardHeight];
		foreach(GameObject myObject in GameObject.FindGameObjectsWithTag("gridcell")){
			GridCell gridCell = myObject.GetComponent<GridCell>();
			board[index,jindex] = gridCell;
			gridCell.boardPosition = new Vector2(index,jindex);
			index++;
			if(index> boardWidth - 1){
				index=0;
				jindex++;
			}
			gridCell.transform.position = new Vector3(gridCell.boardPosition.x + .5f, gridCell.transform.position.y, gridCell.boardPosition.y + .5f) - new Vector3(boardWidth/2.0f, 0f, boardHeight/2.0f);
			if((gridCell.transform.position.x >= .49999f && gridCell.transform.position.x <=1.000001f) && gridCell.transform.position.z == .5f){
				player.currentGridCell = gridCell;
				player.currentGridCellBoardPosition = gridCell.boardPosition;
			}
		}

	}

	public void setPlayerTarget(Vector2 targetGridPosition, GridCell targetGrid){
		player.clearPath();
		resetGameBoard();
		player.destinationGridCell = targetGrid;
		player.myPath = astar.calculatePath();
		//player.printPath(player.myPath);
		player.destinationGrid = targetGridPosition;
	}

	public void resetGameBoard(){
		for(int i = 0; i < boardWidth; i++){
			for(int j = 0; j < boardHeight; j++){
				board[i,j].fValue = 9001;
				board[i,j].gValue = 0;
				board[i,j].hValue = 0;
				board[i,j].parentGridCell = null;
			}
		}
	}
}
